os

您所在的位置:网站首页 makefile 命令行 变量 os

os

2023-05-27 13:12| 来源: 网络整理| 查看: 265

生成目录树中的文件名,方式是按上->下或下->上顺序浏览目录树。对于以 top 为根的目录树中的每个目录(包括 top 本身),它都会生成一个三元组 (dirpath, dirnames, filenames)。

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (including symlinks to directories, and excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified.

如果可选参数 topdown 为 True 或未指定,则在所有子目录的三元组之前生成父目录的三元组(目录是自上而下生成的)。如果 topdown 为 False,则在所有子目录的三元组生成之后再生成父目录的三元组(目录是自下而上生成的)。无论 topdown 为何值,在生成目录及其子目录的元组之前,都将检索全部子目录列表。

当 topdown 为 True 时,调用者可以就地修改 dirnames 列表(也许用到了 del 或切片),而 walk() 将仅仅递归到仍保留在 dirnames 中的子目录内。这可用于减少搜索、加入特定的访问顺序,甚至可在继续 walk() 之前告知 walk() 由调用者新建或重命名的目录的信息。当 topdown 为 False 时,修改 dirnames 对 walk 的行为没有影响,因为在自下而上模式中,dirnames 中的目录是在 dirpath 本身之前生成的。

默认将忽略 scandir() 调用中的错误。如果指定了可选参数 onerror,它应该是一个函数。出错时它会被调用,参数是一个 OSError 实例。它可以报告错误然后继续遍历,或者抛出异常然后中止遍历。注意,可以从异常对象的 filename 属性中获取出错的文件名。

walk() 默认不会递归进指向目录的符号链接。可以在支持符号链接的系统上将 followlinks 设置为 True,以访问符号链接指向的目录。

备注

注意,如果链接指向自身的父目录,则将 followlinks 设置为 True 可能导致无限递归。walk() 不会记录它已经访问过的目录。

备注

如果传入的是相对路径,请不要在恢复 walk() 之间更改当前工作目录。walk() 不会更改当前目录,并假定其调用者也不会更改当前目录。

下面的示例遍历起始目录内所有子目录,打印每个目录内的文件占用的字节数,CVS 子目录不会被遍历:

import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories

在下一个示例(shutil.rmtree() 的简单实现)中,必须使树自下而上遍历,因为 rmdir() 只允许在目录为空时删除目录:

# Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))

引发一个 审计事件 os.walk,附带参数 top, topdown, onerror, followlinks。

在 3.5 版更改: 现在,本函数调用的是 os.scandir() 而不是 os.listdir(),从而减少了调用 os.stat() 的次数而变得更快。

在 3.6 版更改: 接受一个 path-like object。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3